package com.jucai.pppeiyouclient.weidget.photo;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.comm.CommonMethod;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.ScreenUtil;
import com.jucai.pppeiyouclient.utils.ToastUtils;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;


/**
 * Created by Administrator on 2017/1/7.
 */

public class PhotoActivity extends Activity implements View.OnClickListener, AllPictureDirPopupWindow.OnImageDirSelected {
    private Activity activity;
    private TextView photo_allPhotoTv;
    private TextView photo_previewTv;
    private TextView photo_sureTv;

    private ArrayList<String> pathList = new ArrayList<String>();
    private ArrayList<String> pathListTemp = new ArrayList<String>();
    /**
     * 防止同一个文件夹的多次扫描
     */
    private HashSet<String> oneDirPaths = new HashSet<String>();
    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<AllPictureImageInfo> allImageFolders = new ArrayList<AllPictureImageInfo>();
    /**
     * 当前显示的文件夹图片
     */
    private List<String> nowImages = new ArrayList<String>();
    /**
     * 所有的图片
     */
    private List<String> firstAllImages = new ArrayList<String>();
    private int totalCount = 0;
    private AllPictureAdapter pictureAdapter;
    private GridView photo_gridView;
    private AllPictureDirPopupWindow myPopupWindowForAllImageFolders;
    private AllPictureImageInfo imageFolderFirst;
    private boolean flag = true;
    private ListView listview;
    private int mScreenHeight = 0;

    /**
     * 相册扫面完成
     */
    private android.os.Handler myHandler = new android.os.Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {// 相册扫面完成
                totalCount = nowImages.size();
                firstAllImages = nowImages;
                imageFolderFirst.setCount(totalCount);
                pictureAdapter = new AllPictureAdapter(activity, nowImages, R.layout.all_picture_item_addnew, "", pathListTemp);
                photo_gridView.setAdapter(pictureAdapter);
                initListDirPopupWindw();
            }

        }

        ;
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.photo_allPhotoTv:
                if (myPopupWindowForAllImageFolders != null && !myPopupWindowForAllImageFolders.isShowing()) {
                    myPopupWindowForAllImageFolders.showAsDropDown(view);
                } else if (myPopupWindowForAllImageFolders != null && myPopupWindowForAllImageFolders.isShowing()) {
                    myPopupWindowForAllImageFolders.dismiss();
                    listview.setSelection(0);
                }

                break;

            case R.id.photo_previewTv:
                if (pathListTemp.size() != 0) {
                    /**
                     * 图片预览
                     */
                    String urls[] = new String[pathListTemp.size()];
                    for (int i = 0; i < pathListTemp.size(); i++) {
                        urls[i] = "file://" + pathListTemp.get(i);
                    }
                    CommonMethod.bigImageBrower(activity, 0, urls);
                } else {
                    ToastUtils.showToast("您还没有选择任何图片");
                }

                break;

            case R.id.photo_sureTv:
                nowImages = firstAllImages;
                pathList.clear();
                for (int i = 0; i < pathListTemp.size(); i++) {
                    pathList.add(pathListTemp.get(i));
                }
                pathListTemp.clear();
                pathList.add("0");
                Intent intent = new Intent();
                intent.putExtra("pathList", pathList);
                setResult(Activity.RESULT_OK, intent);
                finish();

                break;

            default:

                break;

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;

        /**
         * 透明状态栏
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        initView();
        setListener();
        initData();

    }

    protected void initView() {
        setContentView(R.layout.all_picture_activity_photo);
        ScreenUtil.setStatusColor(this, findViewById(R.id.photo_root), getString(R.string.app_theme_color_one));

        mScreenHeight = ScreenUtil.getScreenHeight(activity);

        photo_gridView = (GridView) findViewById(R.id.photo_gridView);

        photo_allPhotoTv = (TextView) findViewById(R.id.photo_allPhotoTv);
        photo_previewTv = (TextView) findViewById(R.id.photo_previewTv);
        photo_sureTv = (TextView) findViewById(R.id.photo_sureTv);

        final RelativeLayout photo_headRl = (RelativeLayout) findViewById(R.id.photo_headRl);
        final RelativeLayout photo_bottomRl = (RelativeLayout) findViewById(R.id.photo_bottomRl);
        CommonMethod.setViewCancelListener(photo_bottomRl, new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int magin = ScreenUtil.dip2px(activity, 3);
                ScreenUtil.setRelativeLayoutMagin(activity, magin, photo_headRl.getHeight() + magin, magin, photo_bottomRl.getHeight() + magin, photo_gridView);
            }
        });

    }

    protected void setListener() {
        photo_allPhotoTv.setOnClickListener(this);
        photo_previewTv.setOnClickListener(this);
        photo_sureTv.setOnClickListener(this);

    }

    protected void initData() {
        ArrayList<String> pathListBack = (ArrayList<String>) getIntent().getSerializableExtra("pathList");
        if (pathListTemp.size() > 0) {
            pathListTemp.clear();
        }
        if (pathListBack.size() > 0) {
            for (int i = 0; i < pathListBack.size() - 1; i++) {
                LogUtils.e("图片路径：" + pathListBack.get(i));
                pathListTemp.add(pathListBack.get(i));
            }
        }
        pathListBack.clear();
        scanPictrue();

    }

    /**
     * 扫描手机上jpg／jpeg／png格式的图片
     */
    private void scanPictrue() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;

                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = activity.getContentResolver();
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpg", "image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
                while (mCursor.moveToNext()) {
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));

                    nowImages.add(path);
                    if (firstImage == null)
                        firstImage = path;
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    if (flag) {
                        imageFolderFirst = new AllPictureImageInfo();
                        imageFolderFirst.setDir("/所有图片");
                        imageFolderFirst.setFirstImagePath(path);
                        imageFolderFirst.setAllPicture(flag);
                        allImageFolders.add(imageFolderFirst);
                        flag = false;
                    }
                    AllPictureImageInfo imageFloder = null;
                    if (oneDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        oneDirPaths.add(dirPath);
                        imageFloder = new AllPictureImageInfo();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }

                    int picSize = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    }).length;
                    totalCount += picSize;
                    imageFloder.setCount(picSize);
                    allImageFolders.add(imageFloder);

                }
                mCursor.close();
                oneDirPaths = null;
                Message message = new Message();
                message.what = 1;
                myHandler.sendMessage(message);

            }
        }).start();
    }

    /**
     * 初始化展示文件夹的popupWindw
     */
    private void initListDirPopupWindw() {
        View view = CommonMethod.getView(this, R.layout.all_picture_layout_listdir);
        listview = (ListView) view.findViewById(R.id.id_list_dir);
        RelativeLayout bottom = (RelativeLayout) view.findViewById(R.id.bottom);
        bottom.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                myPopupWindowForAllImageFolders.dismiss();
                listview.setSelection(0);
            }
        });
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) listview
                .getLayoutParams();
        params.height = mScreenHeight / 3 * 2;
        listview.setLayoutParams(params);
        myPopupWindowForAllImageFolders = new AllPictureDirPopupWindow(LinearLayout.LayoutParams.MATCH_PARENT, (int) (mScreenHeight),
                allImageFolders, view);
        myPopupWindowForAllImageFolders.setAnimationStyle(R.style.animBottomInBottomOut);
        /**
         * 设置选择文件夹的回调
         */
        myPopupWindowForAllImageFolders.setOnImageDirSelected(this);
        myPopupWindowForAllImageFolders.setFocusable(false);
    }

    /**
     * 选择照片文件夹
     */
    @Override
    public void selected(AllPictureImageInfo floder) {
        myPopupWindowForAllImageFolders.dismiss();
        listview.setSelection(0);

        if (floder.isAllPicture()) {
            nowImages = firstAllImages;
            pictureAdapter = new AllPictureAdapter(activity, nowImages, R.layout.all_picture_item_addnew, "", pathListTemp);
            photo_gridView.setAdapter(pictureAdapter);
        } else {
            nowImages = Arrays.asList(new File(floder.getFirstImagePath()).getParentFile().list(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String filename) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png")) {
                        return true;
                    }
                    return false;
                }
            }));
            pictureAdapter = new AllPictureAdapter(activity, nowImages, R.layout.all_picture_item_addnew, floder.getDir(), pathListTemp);
            photo_gridView.setAdapter(pictureAdapter);
        }
    }

}
